import threading
import tkinter


class FrequencyController:
    def __init__(self, interval=None, function=None, interval_reduction=None, interval_increases=None,
                 specific_stop=None, stop_callback=None, *args, **kwargs):
        self._interval = interval
        self._function = function
        self._interval_reduction = interval_reduction
        self._interval_increases = interval_increases
        self._specific_stop = specific_stop
        self._stop_callback = stop_callback
        self._running = False  # 用于跟踪计时器是否正在运行
        self._timer = None  # 用于存储定时器对象
        self._args = args  # 保存位置参数
        self._kwargs = kwargs  # 保存关键字参数

    def frequency_controller(self):
        if not self._running:
            return  # 如果计时器没有运行，则返回

        self._function(*self._args, **self._kwargs)  # 调用你的函数，并传递参数

        # 调整间隔
        if self._interval_reduction is not None:
            if self._interval > 1:
                self._interval -= self._interval_reduction
        elif self._interval_increases is not None:
            self._interval += self._interval_increases

        # 特定值就停止
        if self._specific_stop is not None:
            if self._interval_reduction is not None:
                if self._interval <= self._specific_stop:
                    self.stop()
                    return
            elif self._interval_increases is not None:
                if self._interval >= self._specific_stop:
                    self.stop()
                    return

        # 重新启动定时器
        self._timer = threading.Timer(self._interval / 1000.0, self.frequency_controller)
        self._timer.start()

    def start(self):
        if not self._running:  # 如果计时器没有运行
            self._running = True
            self.frequency_controller()  # 启动计时器

    def stop(self):
        if self._running:  # 如果计时器正在运行
            self._running = False
            if self._timer is not None:
                self._timer.cancel()  # 取消定时器
            if self._stop_callback is not None:
                self._stop_callback()  # 调用停止回调函数


if __name__ == '__main__':
    def your_function():
        window.bell()  # 发出提示音


    def on_counter_stop():
        window.quit()  # 退出程序


    window = tkinter.Tk()
    window.withdraw()

    counter = FrequencyController(interval=200, function=your_function, interval_reduction=2, specific_stop=100,
                                  stop_callback=on_counter_stop)
    counter.start()

    window.mainloop()
